package com.wh.wisdomsite.xbox.server.controller.ba;

import com.wh.wisdomsite.xbox.ba.entity.FileInUtil;
import com.wh.wisdomsite.xbox.ba.service.IFileService;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.annotation.ModuleTypeEnum;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.ba.MinioUpFileIn;
import com.wh.wisdomsite.xbox.pojo.ba.MinioUpFileOut;
import com.wh.wisdomsite.xbox.pojo.ba.UploadIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.IpUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传控制器
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.common
 * @author: 谢泽鹏
 * @date: 2018-09-20 11:13
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping( value = "/upload")
public class UploadController {

    private static final Log logger = LogFactory.getLog(UploadController.class);

    @Autowired
    private IFileService fileService;



    /**
     * 上传文件
     * @param uploadfile
     * @param response
     * @param request
     * @param uploadIn
     */
    @RequestMapping( value = "/uploadFile.do" , method = RequestMethod.POST)
    public void uploadFile(@RequestParam(value = "uploadfile", required = true) MultipartFile uploadfile, HttpServletResponse response, HttpServletRequest request, UploadIn uploadIn){
        CommonResult result = new CommonResult();
        String repsonsText = "";
        try {
            logger.info("附件上传->>uploadFile->>开始");
            List<MultipartFile> listFile = new ArrayList<>();
            listFile.add(uploadfile);

            //获取上传磁盘文件
            //File[] fileArrays = FileTool.getHttpFiles(request);
            //构建上传文件模型
            //获取用户编号
            String userId = UserUtils.getCurrentUser().getUsId();
            MinioUpFileIn minioUpFileIn = new MinioUpFileIn();
            minioUpFileIn.setModelName(uploadIn.getModelName());
            minioUpFileIn.setModelCode(uploadIn.getModelCode());
            minioUpFileIn.setFunName(uploadIn.getFunName());
            minioUpFileIn.setFunCode(uploadIn.getFunCode());
            minioUpFileIn.setFkType(ModuleTypeEnum.valueOf(uploadIn.getFkType()));
            minioUpFileIn.setBusinessId(userId);

            //未选择上传附件
            if(null == listFile || 0 == listFile.size()){
                result.setCode(Constants.CODE_FAIL);
                result.setMessage("上传附件为空！");
                if(IpUtils.isIE(request)){
                    repsonsText = "{code: '" + result.getCode()  + "', message: '" + result.getMessage() + "', result: { } }";
                    ResManager.getTextOut(response).print(repsonsText);
                }else {
                    ResManager.getJsonOut(response).print(JsonUtil.Json2All(result));
                }
                    return;
            }
            //上传对象
            FileInUtil fileInUtil = null;
            if(listFile.size() == 1){
                //单附件上传
                fileInUtil = new FileInUtil(listFile.get(0).getOriginalFilename(), listFile.get(0).getBytes());
                result = fileService.uploadFile(fileInUtil, minioUpFileIn);
            }else{
                //多附件上传
                List<FileInUtil> fileInUtils = new ArrayList<>();
                for(int i = 0; i < listFile.size(); i++){
                    fileInUtil = new FileInUtil(listFile.get(i).getOriginalFilename(), listFile.get(i).getBytes());
                    fileInUtils.add(fileInUtil);
                }
                result = fileService.uploadFile(fileInUtils, minioUpFileIn);
            }
            logger.info("附件上传->>uploadFile->>结束");
        } catch (Exception e){
            e.printStackTrace();
            result.setCode(Constants.CODE_FAIL);
            result.setMessage("文件上传失败！");
            logger.error("附件上传->>uploadFile->>Exception " + e.getMessage());
        }
        if(IpUtils.isIE(request)){
            MinioUpFileOut minioUpFileOut = (MinioUpFileOut)result.getResult();
            repsonsText = "{'code': '" + result.getCode()  + "', 'message': '" + result.getMessage() + "', 'result': {'fileId': '" + minioUpFileOut.getFileId() + "', 'url': '" + minioUpFileOut.getUrl() + "', 'size': '" + minioUpFileOut.getSize() + "', 'fix': '" + minioUpFileOut.getFix() + "', 'md5': '" + minioUpFileOut.getMd5() + "' }}";
            ResManager.getTextOut(response).print(repsonsText);
        }else{
            //其他浏览器输出
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(result));
        }
    }
}






